//
//  ZPAuthStore.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/21.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPAuthStore.h"

@interface ZPAuthStore ()
{
    NSMutableDictionary  *userInfoDic;
}

@property (nonatomic, copy) NSString *accessToken;
@property (nonatomic, assign)NSInteger memberId;
@end


@implementation ZPAuthStore

ZPSingletonM(ZPAuthStore)

@synthesize accessToken = accessToken_;
@synthesize memberId = memberId_;

- (instancetype)init
{
    self = [super init];
    if( self )
    {
        [self updateWithUserDefaults];
        [self resetUserInfoDictionary]; // 重置用户信息
    }
    return self;
}



-(NSMutableDictionary *)userToDic
{
    if (userInfoDic) {
        return userInfoDic;
    }else {
        [self  resetUserInfoDictionary];
        return userInfoDic;
    }
}


// 重置字段
- (void)resetUserInfoDictionary
{
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    
    [dic safeSetObject:dataDic[@"memberId"] forKey:@"memberId"];
    [dic safeSetObject:dataDic[@"token"] forKey:@"token"];
    [dic safeSetObject:dataDic[@"userName"] forKey:@"userName"];
    [dic safeSetObject:dataDic[@"headUrl"] forKey:@"headUrl"];
    [dic safeSetObject:dataDic[@"mobile"] forKey:@"mobile"];
    [dic safeSetObject:dataDic[@"passwd"] forKey:@"passwd"];
    [dic safeSetObject:dataDic[@"cityId"] forKey:@"cityId"];
    [dic safeSetObject:dataDic[@"cityName"] forKey:@"cityName"];
    [dic safeSetObject:dataDic[@"deviceID"] forKey:@"deviceID"];
    
    userInfoDic = [NSMutableDictionary  dictionaryWithDictionary:dic];
    ZPLog(@"userInfoDic == %@",userInfoDic);
}



// 获取登录token
- (NSString *)accessToken
{
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    self.accessToken = dataDic[@"token"];
    return accessToken_;
}


// 存字段
-(void)dicToUserEntity:(NSMutableDictionary *)dic
{
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    if (!dataDic) {
        dataDic =[[NSMutableDictionary alloc]init];
    }
    [dataDic safeSetObject:dic[@"userName"] forKey:@"userName"];
    [dataDic safeSetObject:dic[@"access_token"] forKey:@"token"];
    [dataDic safeSetObject:dic[@"mobile"] forKey:@"mobile"];
    [dataDic safeSetObject:dic[@"memberid"] forKey:@"memberId"];
    [dataDic safeSetObject:dic[@"score"] forKey:@"score"];
    [dataDic safeSetObject:dic[@"totalConsumption"] forKey:@"totalConsumption"];
    [dataDic safeSetObject:dic[@"passwd"] forKey:@"passwd"];
    
    [dataDic writeToFile:homePath atomically:YES];
    ZPLog(@"dataDic == %@",dataDic);
}


// 获取memberId
- (NSInteger)memberId {
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    self.memberId = [dataDic[@"memberId"] integerValue];
    return memberId_;
}


- (void)updateWithUserDefaults {
    
}

//- (BOOL)hasExpired {
//    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
//    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
//    self.expiresIn = dataDic[@"expiresIn"];
//    NSDate *date = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate: date];
//    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
//    NSDate *thirtyMinutesBeforeExpires = [self.expiresIn dateByAddingTimeInterval:21600];
//    if([localeDate compare:thirtyMinutesBeforeExpires] == NSOrderedAscending) {
//        return NO;
//    }
//    else {
//        return YES;
//    }
//}


- (void)clear
{
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:homePath])
    {
        NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
        [dataDic setValue:@"" forKey:@"memberId"];
        [dataDic setValue:@"" forKey:@"token"];
        [dataDic setValue:@"" forKey:@"userName"];
        [dataDic setValue:@"" forKey:@"headUrl"];
        [dataDic setValue:@"" forKey:@"mobile"];
        [dataDic setValue:@"" forKey:@"passwd"];
//        [dataDic setValue:@"" forKey:@"cityId"];
//        [dataDic setValue:@"" forKey:@"cityName"];
//        [dataDic setValue:@"" forKey:@"deviceID"];
    
        [dataDic writeToFile:homePath atomically:YES];
    }
    
    [self  resetUserInfoDictionary];
    [self  setWebViewCookiesWithType:1];
}




-(void)saveTokenAndInitWithToken:(NSString *)token
{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/UserInfo.plist"];
    if (![fileManager fileExistsAtPath:homePath])
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"plist"];
        // bundle文件复制到沙盒中
        [fileManager copyItemAtPath:path toPath:homePath error:nil];
    }
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    [dataDic setObject:token forKey:@"devicetoken"];
    [dataDic writeToFile:homePath atomically:YES];
    
    [self  resetUserInfoDictionary];
    
}



- (void)updateWithSuccessDictionary:(NSDictionary *)dic {
    
}


//设置传1     删除传0
- (void)setWebViewCookiesWithType:(NSInteger)type
{
    //清除cookies
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    
    
    if (type == 1) {
        NSMutableDictionary *dataDic = [self userToDic];
        for (int i = 0; i < 4; i ++) {
            NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
            if (i == 0) {
                [cookieProperties setObject:@"deviceid" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[NSString stringWithFormat:@"%@",[dataDic  objectForKey:@"deviceID"]] forKey:NSHTTPCookieValue];
            }else if (i == 1) {
                [cookieProperties setObject:@"version" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[NSString  stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] forKey:NSHTTPCookieValue];
            }else if (i == 2) {
                NSString  *cityId = [dataDic objectForKey:@"cityId"];
                if (cityId && ![cityId  isEqual:@""]) {
                    NSString * encodedCityId = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)cityId, NULL, NULL,  kCFStringEncodingUTF8 ));
                    [cookieProperties setObject:@"cityid" forKey:NSHTTPCookieName];
                    [cookieProperties setObject:[NSString  stringWithFormat:@"%@",encodedCityId] forKey:NSHTTPCookieValue];
                }
            }else if (i == 3) {
                NSString  *cityName = [dataDic objectForKey:@"cityName"];
                if (cityName && ![cityName  isEqual:@""]) {
                    NSString * encodedCityName = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)cityName, NULL, NULL,  kCFStringEncodingUTF8 ));
                    [cookieProperties setObject:@"cityname" forKey:NSHTTPCookieName];
                    [cookieProperties setObject:[NSString  stringWithFormat:@"%@",encodedCityName] forKey:NSHTTPCookieValue];
                }
            }
            
            if (cookieProperties.count > 0) {
                [cookieProperties setObject:WebViewCookieDomain forKey:NSHTTPCookieDomain];
                [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
                NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
        
        
        
        NSString  *memberId = [dataDic  objectForKey:@"memberId"];
        if (!memberId || [memberId  isEqual:@""]) {
            [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCellWebView" object:nil];
            return;
        }
        
        NSString  *token = [dataDic  objectForKey:@"token"];
        if (!token || [token  isEqual:@""]) {
            [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCellWebView" object:nil];
            return;
        }
        
        for (int i = 0; i < 4; i ++) {
            NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
            if (i == 0) {
                [cookieProperties setObject:@"edmemberid" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[NSString  stringWithFormat:@"%@",memberId] forKey:NSHTTPCookieValue];
            }else if (i == 1) {
                [cookieProperties setObject:@"edtoken" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[NSString  stringWithFormat:@"%@",token] forKey:NSHTTPCookieValue];
            }else if (i == 2) {
                [cookieProperties setObject:@"edpassword" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[[NSString stringWithFormat:@"%@",[dataDic  objectForKey:@"passwd"]] zp_md5String] forKey:NSHTTPCookieValue];
            }else if (i == 3){
                NSString  *userName = [NSString  stringWithFormat:@"T_%@",[dataDic objectForKey:@"mobile"]];
                NSString * encodedUserName = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)userName, NULL, NULL,  kCFStringEncodingUTF8 ));
                [cookieProperties setObject:@"edusername" forKey:NSHTTPCookieName];
                [cookieProperties setObject:[NSString  stringWithFormat:@"%@",encodedUserName] forKey:NSHTTPCookieValue];
            }
            
            if (cookieProperties.count > 0) {
                [cookieProperties setObject:WebViewCookieDomain forKey:NSHTTPCookieDomain];
                [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
                NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
    
        }
        
        [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCellWebView" object:nil];
        
    }else {
        [self  deleteCookies];
    }
    
}



- (void)deleteCookies
{
    //清除cookies
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
}

- (BOOL)isLogin
{
    NSString  *memberId = [self.userToDic  objectForKey:@"memberId"];
    if (memberId && ![memberId  isEqual:[NSNull  null]] && ![memberId  isEqual:@""]) {
        return YES;
    }
    
    return NO;
}


@end
